package app.caihan.wanandroid.ui.main

import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import app.caihan.scframe.constant.DEBUG_TAG
import app.caihan.scframe.databind.DataBindingConfig
import app.caihan.scframe.ktx.setSingleOnItemClickListener
import app.caihan.wanandroid.BR
import app.caihan.wanandroid.R
import app.caihan.wanandroid.base.WanBaseFragment
import app.caihan.wanandroid.model.bean.Article
import app.caihan.wanandroid.model.bean.BannerBean
import app.caihan.wanandroid.ui.web.BrowserUi
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.util.BannerUtils


/**
 *
 *
 * @author Seven-C
 * @date 2020/8/11
 */
class MainFragment : WanBaseFragment<MainFragmentModel>() {

    private val cid by lazy { arguments?.getInt(CID) }
    private val mAdapter by lazy { MainArticleListAdapter() }
    private val banner: Banner<BannerBean, BannerImageAdapter>
            by lazy { Banner<BannerBean, BannerImageAdapter>(requireActivity()) }

    companion object {
        private const val CID = "projectCid"
        fun newInstance(cid: Int): MainFragment {
            val fragment = MainFragment()
            val bundle = Bundle()
            bundle.putInt(CID, cid)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.fragment_main
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(BR.vm).addBindingParam(BR.adapter, mAdapter)
    }

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun createObserver() {
        mAdapter.apply {
            setSingleOnItemClickListener { adapter, view, position ->
                val item: Article = mAdapter.data[position]
                toast("点击了${item.author} 的 ${item.title}")
                BrowserUi.startArticleDetail(
                    this@MainFragment.requireContext(),
                    item.link,
                    item.title
                )
            }
            if (headerLayoutCount > 0) {
                removeAllHeaderView()
            }
            addHeaderView(banner)
        }
        mViewModel.apply {
            articleList.observe(this@MainFragment, Observer {
                LogUtils.dTag(DEBUG_TAG," articleList.observe")
                if (it.curPage == 0) {
                    mAdapter.setNewInstance(it.datas.toMutableList())
                } else {
                    mAdapter.addData(it.datas.toMutableList())
                }
                mAdapter.isUseEmpty = true
            })
            banners.observe(this@MainFragment, Observer {
                banner.adapter.setDatas(it)
            })
        }
        banner.apply {
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(200f)
            )
            addBannerLifecycleObserver(this@MainFragment)
            indicator = CircleIndicator(this.context)
            setBannerRound(20f)
            adapter = BannerImageAdapter(ArrayList<BannerBean>())
            setOnBannerListener { _, position ->
                toast("点击了$position 的 ${adapter.getData(position).id}")
            }
        }
        appViewModel.run {
            userInfo.observeInFragment(this@MainFragment, Observer {
                LogUtils.dTag(
                    DEBUG_TAG,
                    "${javaClass.simpleName} :: observe appViewModel.userinfo = $it"
                )
            })
            appColor.observeInFragment(this@MainFragment, Observer {
                LogUtils.dTag(
                    DEBUG_TAG,
                    "${javaClass.simpleName} :: observe appViewModel.appColor = $it"
                )
            })
        }
    }

    override fun lazyLoadData() {
        mViewModel.text.value = "main fragment $cid"
        mViewModel.autoRefresh()
    }


    class BannerImageAdapter(imageUrls: List<BannerBean>) :
        BannerAdapter<BannerBean, BannerImageAdapter.ImageHolder>(imageUrls) {


        override fun onCreateHolder(parent: ViewGroup?, viewType: Int): ImageHolder {
            val imageView = ImageView(parent!!.context)
            val params = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            imageView.layoutParams = params
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            //通过裁剪实现圆角
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                BannerUtils.setBannerRound(imageView, 20f)
            }
            return ImageHolder(imageView)
        }

        override fun onBindView(holder: ImageHolder, data: BannerBean, position: Int, size: Int) {
            Glide.with(holder.itemView)
                .load(data.imagePath)
                .into(holder.imageView)
        }

        class ImageHolder(view: View) : RecyclerView.ViewHolder(view) {
            var imageView: ImageView = view as ImageView
        }
    }
}